<template>
  <div class="el-select orgset-treeselect">
    <treeselect
      v-bind="$attrs"
      :value="treeValue"
      :options="warehouseList"
      :searchable="true"
      :clearable="true"
      :show-count="true"
      :disabled="!editable"
      :flat="true"
      :multiple="false"
      :is-default-expanded="true"
      :normalizer="normalizer"
      placeholder="选择仓库"
      @select="warehouseSelect"
      v-on="$listeners"
    />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getWarehouseByCpyCode } from '@/api/base/warehouse'

export default {
  components: { Treeselect },
  model: {
    prop: 'value' // , // 自定义prop属性
    // event: 'handSelect' // 自定义它的触发方法名
  },
  props: {
    value: {
      type: String,
      default: null,
      required: false
    },
    valueField: {
      type: String,
      default: 'id',
      required: false
    },
    curId: {
      type: String,
      default: null,
      required: false
    },
    editable: {
      type: Boolean,
      default: true,
      required: false
    },
    paramData: {
      type: Object,
      default: null,
      required: false
    }
  },
  data() {
    return {
      warehouseList: []
    }
  },
  computed: {
    treeValue: {
      get() {
        if (this.value === '') {
          return null
        }
        return this.value
      },
      set(val) {
        this.value = val
      }
    }
  },
  watch: {
    curId() {
      // 获取所有仓库
      getWarehouseByCpyCode(this.curId).then(res => {
        this.warehouseList = res.data
      })
    }
  },
  created() {
    if (!this.curId) {
      if (this.warehouseList.length <= 0) {
        getWarehouseByCpyCode(this.curId).then(res => {
          this.warehouseList = res.data
          if (this.editable && !this.treeValue && this.warehouseList.length > 0) {
            this.$emit('setDefaultWarehouseId', this.warehouseList[0].id, this.paramData)
          }
        })
      }
    }
  },
  mounted() {
  },
  methods: {
    normalizer(node) {
      return {
        id: node[this.valueField],
        label: node.warehouseName
      }
    },
    warehouseSelect(node, instanceId) {
      this.$emit('warehouseSelect', node[this.valueField], this.paramData)
    }
  }
}
</script>
<style scoped>
  .orgset-treeselect{
    padding-left: 3px;
    height:25px;
  }
</style>
